﻿using Model.DocumentDB;
using System;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;

namespace Studio.DocumentDB.Dialogs
{
    /// <summary>Window querying the user about a DocDB account credentials.</summary>
    public partial class AccountCredentialsWindow : Window
    {
        /// <summary>Studio model.</summary>
        /// <remarks>Input by consumer.</remarks>
        public StudioViewModel Studio { get; set; }

        /// <summary>Constructor.</summary>
        public AccountCredentialsWindow()
        {
            InitializeComponent();

            ValidateForm();
        }

        private async void Ok_Click(object sender, RoutedEventArgs e)
        {
            if (Studio != null)
            {
                await ErrorHelper.HandleAsync(
                    async () =>
                    {
                        var id = idBox.Text;
                        var key = keyBox.Text;
                        var account = new AccountViewModel(id, key, Studio);
                        var waitWindow = new WaitWindow
                        {
                            WaitingTask = SaveNewAcountAsync(account),
                            Owner = Window.GetWindow(this)
                        };

                        waitWindow.ShowDialog();
                        await waitWindow.WaitingTask;
                        DialogResult = true;
                    }, this, "Credentials aren't working:  {0}");
            }
        }

        private async Task SaveNewAcountAsync(AccountViewModel account)
        {
            await account.IsValidAsync();
            Studio.Accounts.Add(account);
            await Studio.Accounts.SaveAsync();
        }

        private void idBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            ValidateForm();
        }

        private void keyBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            ValidateForm();
        }

        private void ValidateForm()
        {
            okButton.IsEnabled = !string.IsNullOrWhiteSpace(idBox.Text)
                && !string.IsNullOrWhiteSpace(keyBox.Text);
        }
    }
}
